07. Adding Methods to Constructors

Adding Methods to Constructors

Question:

Start Quiz:

// Refactor the carlike function in a way
// that allows you to use the method calling 
// syntax with "dot access" as we do below.
var carlike = function(obj, loc) {
    obj.loc = loc;
    return obj;
};

var move = function(car) {
    car.loc++;
};

/////
// Here we want to call move with "dot access"
var amy = carlike({}, 1);
amy.move();
var ben = carlike({}, 9);
ben.move();
describe("TEST: A new carlike object should have a move method.", function() {
  it("\nA new carlike can move: ", function() {
      expect(carlike({}, 1)).to.respondTo('move');
  });
});

describe("TEST: amy should have moved from 1 to 2.", function() {
  it("\nAmy moved from 1 to 2: ", function() {
    amy.loc.should.be.equal(2);
  });
});

describe("TEST: ben should have moved from 9 to 10.", function() {
  it("\nBen moved from 9 to 10: ", function() {
    ben.loc.should.be.equal(10);
  });
});

User's Answer:

(Note: The answer done by the user is not guaranteed to be correct)

// Refactor the carlike function in a way
// that allows you to use the method calling 
// syntax with "dot access" as we do below.
var carlike = function(obj, loc) {
    obj.loc = loc;
    obj.move = function() {
        this.loc++;
    }
    return obj;
};

// var move = function(car) {
//     car.loc++;
// };

/////
// Here we want to call move with "dot access"
var amy = carlike({}, 1);
amy.move();
var ben = carlike({}, 9);
ben.move();
describe("TEST: A new carlike object should have a move method.", function() {
  it("\nA new carlike can move: ", function() {
      expect(carlike({}, 1)).to.respondTo('move');
  });
});

describe("TEST: amy should have moved from 1 to 2.", function() {
  it("\nAmy moved from 1 to 2: ", function() {
    amy.loc.should.be.equal(2);
  });
});

describe("TEST: ben should have moved from 9 to 10.", function() {
  it("\nBen moved from 9 to 10: ", function() {
    ben.loc.should.be.equal(10);
  });
});
Solution: